/*
     * WiFi管理类实现
     */
    #include "WiFiManager.h"
    #include <Arduino.h>

    WiFiManager::WiFiManager(const char* ssid, const char* password) :
        _ssid(ssid),
        _password(password),
        _isConnected(false),
        _reconnectInterval(5000),  // 5秒重连间隔
        _lastReconnectAttempt(0)
    {
    }

    void WiFiManager::begin() {
        Serial.println("初始化WiFi...");
        WiFi.mode(WIFI_STA);  // 设置为Station模式
        WiFi.begin(_ssid, _password);
        _lastReconnectAttempt = millis();
    }

    void WiFiManager::loop() {
        // 检查WiFi连接状态
        if (WiFi.status() != WL_CONNECTED) {
            _isConnected = false;
            
            // 定时重连
            if (millis() - _lastReconnectAttempt > _reconnectInterval) {
                _lastReconnectAttempt = millis();
                Serial.print("尝试连接到WiFi: ");
                Serial.println(_ssid);
                WiFi.reconnect();
            }
        } else if (!_isConnected) {
            // 刚刚连接成功
            _isConnected = true;
            Serial.println("WiFi连接成功!");
            Serial.print("IP地址: ");
            Serial.println(getIpAddress());
            
            // 触发回调
            if (_onConnectionStatusChanged) {
                _onConnectionStatusChanged(true);
            }
        }
    }

    bool WiFiManager::isConnected() const {
        return _isConnected;
    }

    void WiFiManager::setOnConnectionStatusChanged(std::function<void(bool)> callback) {
        _onConnectionStatusChanged = callback;
    }

    String WiFiManager::getIpAddress() const {
        return WiFi.localIP().toString();
    }
    